package com.example.jd.finance.web;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.jd.common.DateUtils;
import com.example.jd.common.InvokeResultUtil;
import com.example.jd.common.SequenceNumUtil;
import com.example.jd.common.enums.BizStatusCodeEnum;
import com.example.jd.common.enums.NumberEnum;
import com.example.jd.common.enums.StatusEnum;
import com.example.jd.finance.entity.MsCustomerRecords;
import com.example.jd.finance.entity.MsWechatIncreaseCustomerDetails;
import com.example.jd.finance.entity.MsWechatIncreaseFriends;
import com.example.jd.finance.entity.MsWechatTotalStatiscs;
import com.example.jd.finance.entity.param.AppInfoLoadServerParam;
import com.example.jd.finance.entity.param.AppLoadNumberParam;
import com.example.jd.finance.entity.param.AppUpdateStateParam;
import com.example.jd.finance.entity.param.LoginStateParam;
import com.example.jd.finance.sever.MsCustomerRecordsService;
import com.example.jd.finance.sever.MsWechatIncreaseCustomerDetailsService;
import com.example.jd.finance.sever.MsWechatIncreaseFriendsService;
import com.example.jd.finance.sever.MsWechatTotalStatiscsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-11-06
 */
@RestController
@Slf4j
@RequestMapping("/msWechatIncreaseFriends")
public class MsWechatIncreaseFriendsController {


    @Autowired
    private MsWechatIncreaseFriendsService msWechatIncreaseFriendsService;

    @Autowired
    SequenceNumUtil sequenceNumUtil;

    @Autowired
    private MsWechatIncreaseCustomerDetailsService msWechatIncreaseCustomerDetailsService;

    @Autowired
    private MsCustomerRecordsService msCustomerRecordsService;

    @Autowired
    private MsWechatTotalStatiscsService msWechatTotalStatiscsService;


    /**
     * 设备登录登出接口
     */
    @PostMapping("/login")
    public InvokeResultUtil<Object> deviceLoginState(@RequestBody LoginStateParam param) {
        if (param == null) {
            return InvokeResultUtil.failure(BizStatusCodeEnum.MISSING_PARAMS.getCode(), "请求参数为空");
        }
        try {
            log.info("MsWechatIncreaseFriendsController-->deviceLoginState入参为：{}", param);
            MsWechatIncreaseFriends one = getMsWechatIncreaseFriends(param.getEnterpriseWechatCode());
            if (param.getIfLogin()) {
                if (one == null) {
                    msWechatIncreaseFriendsService.save(MsWechatIncreaseFriends.generateMsWechatIncreaseFriends(sequenceNumUtil.getNum(),
                            param.getEnterpriseWechatCode(), param.getCurrentDevice(), param.getIsIncreaseFriends()));
                    MsWechatTotalStatiscs t = new MsWechatTotalStatiscs();
                    t.setFriendTotal(param.getIsIncreaseFriends());
                    t.setCurrentApplyTotal(NumberEnum.ZERO.getCode());
                    t.setCurrentApplySuccessTotal(NumberEnum.ZERO.getCode());
                    t.setCurrentDay(LocalDate.now());
                    t.setEnterpriseWechatCode(param.getEnterpriseWechatCode());
                    msWechatTotalStatiscsService.save(t);
                } else {
                    this.updateDeviceStateLoginOut(param.getCurrentDevice(), param.getState(), one.getBid());
                }
            } else {
                this.updateDeviceStateLoginOut(param.getCurrentDevice(), param.getState(), one.getBid());
            }

            return InvokeResultUtil.success("操作成功");
        } catch (Exception e) {
            log.error("MsWechatIncreaseFriendsController--->登录登出接口deviceLoginState异常：", e);

            return InvokeResultUtil.failure(BizStatusCodeEnum.ERROR_SYSTEM.getCode(), "系统异常");
        }
    }


    /**
     * 设备执行任务后 更改设备状态
     */
    @PostMapping("/update")
    public InvokeResultUtil<Object> updateState(@RequestBody AppUpdateStateParam param) {
        if (param == null) {
            return InvokeResultUtil.failure(BizStatusCodeEnum.MISSING_PARAMS.getCode(), "请求参数为空");
        }
        try {
            log.info("MsWechatIncreaseFriendsController-->updateState入参为：{}", param);
            MsWechatIncreaseFriends device = getMsWechatIncreaseFriends(param.getEnterpriseWechatCode());
            if (device == null) {
                return InvokeResultUtil.failure(BizStatusCodeEnum.NOT_FOUND.getCode(), "根据企微号：" + param.getEnterpriseWechatCode() + "未查询到数据信息");
            }
            this.updateDeviceStateLoginOut(param.getCurrentDevice(), param.getState(), device.getBid());

            return InvokeResultUtil.success("操作成功");
        } catch (Exception e) {
            log.error("MsWechatIncreaseFriendsController--->更新updateState异常：", e);

            return InvokeResultUtil.failure(BizStatusCodeEnum.ERROR_SYSTEM.getCode(), "更新异常");
        }
    }

    /**
     * app load task info to server
     */
    @PostMapping("infoLoad")
    public InvokeResultUtil<Object> appInfoLoad(@RequestBody AppLoadNumberParam param) {

        if (param == null || CollectionUtils.isEmpty(param.getList())) {
            return InvokeResultUtil.failure(BizStatusCodeEnum.MISSING_PARAMS.getCode(), "请求参数为空");
        }
        try {
            log.info("MsWechatIncreaseFriendsController-->appInfoLoad入参为：{}", param);
            List<AppInfoLoadServerParam> list = param.getList();
            list.forEach(e -> {
                msWechatIncreaseCustomerDetailsService.save(MsWechatIncreaseCustomerDetails.generateMsWechatIncreaseCustomerDetails(sequenceNumUtil.getNum(),
                        param.getEnterpriseWechatCode(), e.getCustomerBid(), e.getState(), e.getApplyDesc(), e.getApplyTime()));

                this.updateRecords(e.getState(), e.getApplyTime(), e.getCustomerBid());
            });

            updateFriends(param.getCumulativeIncreaseFriends(), param.getIncreaseFriendsTotalDay(), param.getEnterpriseWechatCode());

            LocalDate localDate = LocalDate.now();
            MsWechatTotalStatiscs one = msWechatTotalStatiscsService.getOne(Wrappers.<MsWechatTotalStatiscs>lambdaQuery()
                    .select()
                    .eq(MsWechatTotalStatiscs::getEnterpriseWechatCode, param.getEnterpriseWechatCode())
                    .eq(MsWechatTotalStatiscs::getCurrentDay, localDate)
            );

            MsWechatTotalStatiscs t = new MsWechatTotalStatiscs();
            t.setFriendTotal(param.getCumulativeIncreaseFriends());
            t.setCurrentApplyTotal(param.getIncreaseFriendsTotalDay());
            if (one == null){
                t.setCurrentDay(localDate);
                t.setEnterpriseWechatCode(param.getEnterpriseWechatCode());
                MsWechatTotalStatiscs yesterdayOne = msWechatTotalStatiscsService.getOne(Wrappers.<MsWechatTotalStatiscs>lambdaQuery()
                        .select()
                        .eq(MsWechatTotalStatiscs::getEnterpriseWechatCode, param.getEnterpriseWechatCode())
                        .orderByDesc(MsWechatTotalStatiscs::getCurrentDay)
                        .last("limit 1")
                );
                if (yesterdayOne == null){
                    t.setCurrentApplySuccessTotal(param.getCumulativeIncreaseFriends());
                }else {
                    t.setCurrentApplySuccessTotal(param.getCumulativeIncreaseFriends() - yesterdayOne.getFriendTotal());
                }

                msWechatTotalStatiscsService.save(t);
            }else {
                MsWechatTotalStatiscs yesterday = msWechatTotalStatiscsService.getOne(Wrappers.<MsWechatTotalStatiscs>lambdaQuery()
                        .select()
                        .eq(MsWechatTotalStatiscs::getEnterpriseWechatCode, param.getEnterpriseWechatCode())
                        .orderByDesc(MsWechatTotalStatiscs::getCurrentDay)
                        .last("limit 1, 1")
                );
                if (yesterday == null){
                    MsWechatTotalStatiscs today = msWechatTotalStatiscsService.getOne(Wrappers.<MsWechatTotalStatiscs>lambdaQuery()
                            .select()
                            .eq(MsWechatTotalStatiscs::getEnterpriseWechatCode, param.getEnterpriseWechatCode())
                            .orderByDesc(MsWechatTotalStatiscs::getCurrentDay)
                            .last("limit 1")
                    );
                    if (today == null){
                        t.setCurrentApplySuccessTotal(param.getCumulativeIncreaseFriends());
                    }else {
                        t.setCurrentApplySuccessTotal(param.getCumulativeIncreaseFriends() - today.getCurrentApplySuccessTotal());
                    }

                }else {
                    t.setCurrentApplySuccessTotal(param.getCumulativeIncreaseFriends() - yesterday.getFriendTotal());
                }

                msWechatTotalStatiscsService.update(t, Wrappers.<MsWechatTotalStatiscs>lambdaQuery()
                        .select()
                        .eq(MsWechatTotalStatiscs::getEnterpriseWechatCode, param.getEnterpriseWechatCode())
                        .eq(MsWechatTotalStatiscs::getCurrentDay,localDate)
                );
            }
            return InvokeResultUtil.success("上报成功");
        } catch (Exception e) {
            log.error("MsWechatIncreaseFriendsController--->上报信息appInfoLoad异常：", e);
            return InvokeResultUtil.failure(BizStatusCodeEnum.ERROR_SYSTEM.getCode(), "上报信息异常");
        }

    }


    /**
     * query MsWechatIncreaseFriends
     */
    private MsWechatIncreaseFriends getMsWechatIncreaseFriends(String enterpriseWechatCode) {
        return msWechatIncreaseFriendsService.getOne(Wrappers.<MsWechatIncreaseFriends>lambdaQuery()
                .select()
                .eq(MsWechatIncreaseFriends::getEnterpriseWechatCode, enterpriseWechatCode)
                .eq(MsWechatIncreaseFriends::getStatus, StatusEnum.NORMAL.getCode())

        );
    }

    /**
     * update count friends by enterprise
     */
    private void updateFriends(long cFriends, long iFriends, String eWechatCode) {
        MsWechatIncreaseFriends ms = new MsWechatIncreaseFriends();
        ms.setUpdateTime(LocalDateTime.now());
        ms.setCumulativeIncreaseFriends(cFriends == 0 ? 0 : Integer.parseInt(String.valueOf(cFriends)));
        ms.setIncreaseFriendsTotalDay(iFriends == 0 ? 0 : Integer.parseInt(String.valueOf(iFriends)));
        msWechatIncreaseFriendsService.update(ms, Wrappers.<MsWechatIncreaseFriends>lambdaQuery()
                .select()
                .eq(MsWechatIncreaseFriends::getEnterpriseWechatCode, eWechatCode));
    }

    /**
     * update state by bid
     */
    private void updateRecords(Integer state, String applyTime, Long bid) {
        MsCustomerRecords r = new MsCustomerRecords();
        r.setUpdateTime(LocalDateTime.now());
        r.setState(state);
        r.setApplyTime(DateUtils.stringToLocalDate(applyTime));
        msCustomerRecordsService.update(r, Wrappers.<MsCustomerRecords>lambdaQuery()
                .select()
                .eq(MsCustomerRecords::getBid, bid));
    }


    /**
     * update device state
     */
    private void updateDeviceStateLoginOut(String currentDevice, Integer state, Long bid) {
        MsWechatIncreaseFriends f = new MsWechatIncreaseFriends();
        f.setCurrentDevice(currentDevice);
        f.setUpdateTime(LocalDateTime.now());
        f.setState(state);
        msWechatIncreaseFriendsService.update(f, Wrappers.<MsWechatIncreaseFriends>lambdaQuery()
                .select()
                .eq(MsWechatIncreaseFriends::getBid, bid)
        );
    }
}

